package com.example.sunsg.okhttptest;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.breadtrip.R;
import com.example.designmodel.DesignModelActivity;
import com.example.sunsg.okhttptest.Manager.ThreadPoolManager;
import com.example.sunsg.okhttptest.activity.AnnotationActivity;
import com.example.sunsg.okhttptest.activity.AutoActivity;
import com.example.sunsg.okhttptest.activity.BitmapShaderActivity;
import com.example.sunsg.okhttptest.activity.CameraActivity;
import com.example.sunsg.okhttptest.activity.ConstraintLayoutActivity;
import com.example.sunsg.okhttptest.activity.EventBusActivity;
import com.example.sunsg.okhttptest.activity.FloatViewActivity;
import com.example.sunsg.okhttptest.activity.GlideActivity;
import com.example.sunsg.okhttptest.activity.HorizontalScrollViewWithListViewActivity;
import com.example.sunsg.okhttptest.activity.MoveViewActivity;
import com.example.sunsg.okhttptest.activity.RecyclerViewActivity;
import com.example.sunsg.okhttptest.activity.SlideLeftAndUpActivity;
import com.example.sunsg.okhttptest.activity.SlideRemoveActivity;
import com.example.sunsg.okhttptest.activity.SunsgActivity;
import com.example.sunsg.okhttptest.activity.ThreadPoolTestActivity;
import com.example.sunsg.okhttptest.activity.TouchActivity;
import com.example.sunsg.okhttptest.activity.WaveViewActivity;
import com.example.sunsg.okhttptest.activity.WebviewActivity;
import com.example.sunsg.okhttptest.annotation.FiledAnnotation;
import com.example.sunsg.okhttptest.annotation.MethodAnnotation;
import com.example.sunsg.okhttptest.annotation.ObjectAnnotation;
import com.example.sunsg.okhttptest.annotation.ParamsAnnotation;
import com.example.sunsg.okhttptest.annotation.TestObjectAnnotationBean;
import com.example.sunsg.okhttptest.annotation.TestReflect;
import com.example.sunsg.okhttptest.bean.CallBack;
import com.example.sunsg.okhttptest.bean.Comment;
import com.example.sunsg.okhttptest.bean.CompressImageTask;
import com.example.sunsg.okhttptest.bean.Constant;
import com.example.sunsg.okhttptest.bean.DataParent;
import com.example.sunsg.okhttptest.bean.Introduction;
import com.example.sunsg.okhttptest.bean.KeyValue;
import com.example.sunsg.okhttptest.bean.News;
import com.example.sunsg.okhttptest.bean.SpotDetailList;
import com.example.sunsg.okhttptest.bean.UpLoadSpotList;
import com.example.sunsg.okhttptest.bean.User;
import com.example.sunsg.okhttptest.cuseomannotation.ViewAnnotation;
import com.example.sunsg.okhttptest.http.OkHttpManager;
import com.example.sunsg.okhttptest.retrofit.RetrofitActivity;
import com.example.sunsg.okhttptest.rxjava.RxJavaActivity;
import com.example.sunsg.okhttptest.util.AnnotationUtil;
import com.example.sunsg.okhttptest.util.DownLoadFileUtil;
import com.example.sunsg.okhttptest.util.EncodeUtils;
import com.example.sunsg.okhttptest.util.GsonUtil;
import com.example.sunsg.okhttptest.util.ISODateUtils;
import com.example.sunsg.okhttptest.util.ImageUtil;
import com.example.sunsg.okhttptest.util.SecretUtil;
import com.example.sunsg.okhttptest.util.StorageUtils;
import com.example.sunsg.okhttptest.util.Util;
import com.facebook.drawee.view.SimpleDraweeView;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.Headers;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.litepal.crud.DataSupport;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import butterknife.ButterKnife;

public class MainActivity extends ActionBarActivity implements View.OnClickListener {


    @ViewAnnotation(R.id.scrollview_root)
    ScrollView scrollviewRoot;
    private OkHttpClient mOkHttpClient;
    private User mUser;
    private Button mBtn;
    private ProgressBar mProgressBarYouKu;
    private ProgressBar mProgressBarTaoBao;
    private TextView mTvYouKu;
    private TextView mTvTaoBao;
    @FiledAnnotation(value = R.id.button_sunsg)
    private Button mBtnSuns;


    public MainActivity() {
        super();
    }

    private MainActivity _this;
    @ViewAnnotation(R.id.btn_annotation)
    private Button btnAnnotation;
    @ViewAnnotation(R.id.btn_retrofit)
    private Button btnRetrofit;
    @ViewAnnotation(R.id.btn_desgin_model)
    private Button btnDesginModel;
    @ViewAnnotation(R.id.btn_rx_java)
    Button btnRxJava;
    @ViewAnnotation(R.id.btn_screen_shots)
    Button btnScreenShots;
    @ViewAnnotation(R.id.btn_wave_view)
    Button btnWave;
    @ViewAnnotation(R.id.touch_activity)
    Button touchActivity;

    @ViewAnnotation(R.id.btn_glide)
    Button glide;
    @ViewAnnotation(R.id.btn_bitmap_shader)
    Button bitmapShader;
    @ViewAnnotation(R.id.btn_float_activity)
    Button floatWindowActivity;

    @ViewAnnotation(R.id.btn_thread_pool_activity)
    Button threadPoolActivity;

    @ViewAnnotation(R.id.btn_slide_left_up)
    Button slideLeftUpActivity;
    @ViewAnnotation(R.id.btn_constraintLayout)
    Button btn_constraintLayout;
    @ViewAnnotation(R.id.btn_camera)
    Button btn_camera;
    @ViewAnnotation(R.id.btn_moveview)
    Button btn_moveView;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        AnnotationUtil.injectionView(this);
        _this = this;
        //上传文件
        mBtn = (Button) findViewById(R.id.button_upload_file);
        mBtn.setOnClickListener(this);
        //fresco加载图片
        Button fresco = (Button) findViewById(R.id.button_fresco);
        fresco.setOnClickListener(this);
        //压缩图片
        Button compress = (Button) findViewById(R.id.button_compress_pic);
        compress.setOnClickListener(this);
        //load本地html
        Button local_html = (Button) findViewById(R.id.button_local_html);
        local_html.setOnClickListener(this);
        //pull to zone
        Button pulltozone = (Button) findViewById(R.id.btn_pullto_zone);
        pulltozone.setOnClickListener(this);

        Button threadPool = (Button) findViewById(R.id.btn_thread_pool);
        threadPool.setOnClickListener(this);

        Button litepal = (Button) findViewById(R.id.btn_litepal);
        litepal.setOnClickListener(this);

        Button auteView = (Button) findViewById(R.id.btn_auto_view);
        auteView.setOnClickListener(this);


        Button downLoadApk = (Button) findViewById(R.id.button_download_apk);
        downLoadApk.setOnClickListener(this);

        Button slideBtn = (Button) findViewById(R.id.btn_slide_item);
        slideBtn.setOnClickListener(this);

        Button canceldownLoadApk = (Button) findViewById(R.id.button_cancel_download);
        canceldownLoadApk.setOnClickListener(this);
        Button processSecondActivity = ((Button) findViewById(R.id.btn_second_activity));
        processSecondActivity.setOnClickListener(this);
        Button processServiceBindPool = ((Button) findViewById(R.id.btn_serviece_bindpool));
        processServiceBindPool.setOnClickListener(this);
        Button recyclerview = (Button) findViewById(R.id.btn_recycle);
        recyclerview.setOnClickListener(this);
        Button eventBus = (Button) findViewById(R.id.btn_eventbus3);
        eventBus.setOnClickListener(this);
        btnRetrofit.setOnClickListener(this);

        btnAnnotation.setOnClickListener(this);

        btnDesginModel.setOnClickListener(this);
        btnRxJava.setOnClickListener(this);

        btnScreenShots.setOnClickListener(this);

        btnWave.setOnClickListener(this);

        touchActivity.setOnClickListener(this);

        glide.setOnClickListener(this);

        bitmapShader.setOnClickListener(this);

        floatWindowActivity.setOnClickListener(this);

        threadPoolActivity.setOnClickListener(this);

        slideLeftUpActivity.setOnClickListener(this);

        btn_constraintLayout.setOnClickListener(this);

        btn_camera.setOnClickListener(this);

        btn_moveView.setOnClickListener(this);

        //下载显示
        mProgressBarYouKu = ((ProgressBar) findViewById(R.id.progressBar_youku));
        mProgressBarTaoBao = ((ProgressBar) findViewById(R.id.progressBar_taobao));
        mTvYouKu = ((TextView) findViewById(R.id.tv_youku));
        mTvTaoBao = ((TextView) findViewById(R.id.tv_taobao));

        //listview in scrollview
        Button btnListViewInScrollView = ((Button) findViewById(R.id.btn_horizen_scroll_view));
        btnListViewInScrollView.setOnClickListener(this);

        Button btnSunsgActivity = ((Button) findViewById(R.id.button_sunsg));
        btnSunsgActivity.setOnClickListener(this);

        //清楚cookier
//        new PersistentCookieStore(this).removeAll();
        //请求token
        okHttpGetRequest();
//        downLoadFile(Constant.URL_DOWN_YOUKU_APK_URL);
        String datas = Util.getFromAssets(this, "data");
        DataParent datap = (DataParent) GsonUtil.fromJson(datas, DataParent.class);
        Log.i("test", "datap " + datap.toString());
        loadFrescoCircleImage();
        temp();
        registerEventBus();

        try {
            int pp = "591e984231f0a5786e240f6c".getBytes("UTF-8").length;
            Log.i("push","pp = "+pp);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    /**
     * 临时用
     */
    private boolean run = true;

    private void registerEventBus() {
        EventBus.getDefault().register(this);

    }

    private void unregisterEventBus() {
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void eventBus(EventBusActivity.EventMessage message) {
        Log.i("test", "message = " + message.getTitle() + " content = " + message.getContent());
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterEventBus();
    }

    private void pugongying() {
        String url = "http://www.pgyer.com/apiv1/user/listMyPublished";
        List<KeyValue> keyValues = new ArrayList<>();
        keyValues.add(new KeyValue("uKey", "06cbc51f101c6b67d3710ae1dc3f88aa"));
        keyValues.add(new KeyValue("_api_key", "5a68ab76abcbe216db7da53fdcc56dc0"));
        keyValues.add(new KeyValue("page", "1"));

        OkHttpManager.post(url).params(keyValues).builder().enqueue2(new OkHttpManager.CallBack() {
            @Override
            public void onSuccess(Response response, Object o) throws IOException {
                Log.i("test", "pugongying = " + response.body().string());
            }

            @Override
            public void onFaile(Request request, IOException e) {
//        new TestHeapClass().start();

            }
        });
    }


    private void loadFrescoCircleImage() {
        SimpleDraweeView view = ((SimpleDraweeView) findViewById(R.id.circle));
//        FrescoManager.loadResourceId(R.drawable.huangbo).placeImageHolder(R.drawable.ren).autoPlayAnimations(true).builder().into(view);

//        StringBuilder budild = new StringBuilder("res://");
//        budild.append(getPackageName()).append("/").append(R.drawable.huangbo);
//
//        Uri uri = Uri.parse(budild.toString());
//        ImageRequest request = ImageRequestBuilder.newBuilderWithSource(uri).build();
//
//        DraweeController controller = Fresco.newDraweeControllerBuilder()
//                .setImageRequest(request)
//                .setAutoPlayAnimations(true)
//                .build();
//        RoundingParams roundingParams = view.getHierarchy().getRoundingParams();
////        roundingParams.setRoundAsCircle(true);
//        view.getHierarchy().setRoundingParams(roundingParams);
////        view.getHierarchy().setPlaceholderImage(R.drawable.testgit);
//        view.setController(controller);
//        final ImageView imageView = ((ImageView) findViewById(R.id.im_view));
//        FrescoManager.loadBitmap(Uri.parse(FrescoManager.getResPath(R.drawable.ren)),new BaseBitmapDataSubscriber(){
//            @Override
//            protected void onNewResultImpl(Bitmap bitmap) {
//                Bitmap newbitmap = FrescoManager.createNewBitmap(bitmap);
//                imageView.setImageBitmap(newbitmap);
//            }
//
//            @Override
//            protected void onFailureImpl(DataSource<CloseableReference<CloseableImage>> dataSource) {
//
//            }
//        });

    }

    private void temp() {
        Class classs = TestObjectAnnotationBean.class;
        Annotation[] anns = classs.getAnnotations();
        for (Annotation ann : anns) {
            if (ann instanceof ObjectAnnotation) {
                ObjectAnnotation test = (ObjectAnnotation) ann;
                Log.i("test", "ann.type = " + test.print() + " value = " + test.value());
            }


        }

        Class btnClass = this.getClass();
        Field[] fiels = btnClass.getDeclaredFields();
        for (Field field : fiels) {
            if (field.isAnnotationPresent(FiledAnnotation.class)) {
                FiledAnnotation filedAnnotation = field.getAnnotation(FiledAnnotation.class);
                int id = filedAnnotation.value();
                Log.i("test", "id = " + id);
                if (id > 0) {
                    field.setAccessible(true);
//                    field.set;

                    try {
                        field.set(this, this.findViewById(id));

                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }

                    mBtnSuns.setText("guang");
                }
            }
        }

        Class classReflect = TestReflect.class;
        TestReflect testReflect = new TestReflect();
        try {
            Method method = classReflect.getDeclaredMethod("setName", String.class);
            method.invoke(testReflect, "hhh");
            Method methods = classReflect.getDeclaredMethod("getName");
            String name = (String) methods.invoke(testReflect);
            Log.i("test", "name = " + name);

            Method[] methodss = classReflect.getDeclaredMethods();
            for (Method methodd : methodss) {
                Log.i("test1", " getDeclaredMethods = getname = " + methodd.getName() + " methodd.getDeclaringClass() " + methodd.getDeclaringClass() + " methodd.getDefaultValue()" + methodd.getDefaultValue());
                if (methodd.isAnnotationPresent(MethodAnnotation.class)) {
                    MethodAnnotation methodAnnotation = methodd.getAnnotation(MethodAnnotation.class);
                    if (methodAnnotation != null) {
                        Log.i("test1", "method.name = " + methodd.getName() + "MethodAnnotation.value = " + methodAnnotation.value());
                        Annotation[][] params = methodd.getParameterAnnotations();

                        for(Annotation[] ann11 : params){
                            for(Annotation ann22 : ann11){
                                if(ann22 instanceof ParamsAnnotation){
                                    ParamsAnnotation paramsAnnotation = (ParamsAnnotation) ann22;
                                    Log.i("test1","paramsannotation = "+paramsAnnotation.value());
                                }
                            }
                        }
                    }
                }
            }
            Method[] methods1 = classReflect.getMethods();
            for (Method methoddd : methods1) {
//                Log.i("test1"," getMethods = getname = "+ methoddd.getName() +" methodd.getDeclaringClass() "+methoddd.getDeclaringClass()+" methodd.getDefaultValue()"+methoddd.getDefaultValue());
            }
            Constructor<TestReflect> tfConstructor = TestReflect.class.getDeclaredConstructor();
            try {
                TestReflect tf = tfConstructor.newInstance();
//                Log.i("test1","tf .getname = "+tf.getName() + " tf.getAge = "+tf.getAge());
            } catch (InstantiationException e) {
                e.printStackTrace();
            }

        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        Util.putChannelName(getApplicationContext(), "dksjfksjlf");
        Util.getChannel(getApplicationContext());
        Util.getChannelName(getApplicationContext());

//        switch (""){
//            Files
//        }


        Log.i("test2","counter down = "+ISODateUtils.format(System.currentTimeMillis()));


    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Log.i("main","main onNewIntent");
    }

    private void okHttpGetRequest() {

//        final Request request = new Request.Builder().url(Constant.URL_TOKEN).build();
        OkHttpManager.enqueue(Constant.URL_TOKEN, new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {

            }

            @Override
            public void onResponse(Response response) throws IOException {
                if (response.isSuccessful()) {
                    Log.i("test", "response.body() = " + response.body().string());

                    okHttpPostRequest();

                }
            }
        });

    }

    private void change(String str) {
        str = "abc";
        Log.i("test", "str == " + str);
    }

    private void getUserInfo() {
        OkHttpManager.get("http://api.breadtrip.com/v3/user/2387076450/").builder().enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                if (request != null) {

                }
            }

            @Override
            public void onResponse(Response response) throws IOException {
                if (response.isSuccessful()) {
                    Log.i("test", "response.body() = " + response.body().string());
                }
            }
        });
    }

    private void getSpotDetail() {
        OkHttpManager.get("http://api.breadtrip.com/v2/new_trip/spot/?spot_id=2387670550").builder().enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {

            }

            @Override
            public void onResponse(Response response) throws IOException {
                if (response.isSuccessful()) {
                    Log.i("test", "response.body() = " + response.body().string());
                }
            }
        });
    }


    private void okHttpPostRequest() {
//        09-12 10:18:29.661: E/BreadTrip(16932): stringParmars is [password=123456789, username=Sunsg11, sign=d68d0f7cfab5de4f108a23739d4a73b9]
//         http://api.breadtrip.com/accounts/login/
//        mOkHttpClient.setCookieHandler(new CookieManager(new PersistentCookieStore(getApplicationContext()),CookiePolicy.ACCEPT_ALL));
        List<KeyValue> list = new ArrayList<KeyValue>();
        KeyValue password = new KeyValue("password", "123456");
        KeyValue name = new KeyValue("username", "Sunsg11");
        list.add(password);
        list.add(name);
        String sign = SecretUtil.getSecretSign(list, getApplicationContext());
        list.add(new KeyValue("sign", sign));
//        Log.i("test","url params = "+OkHttpUtil.attachHttpGetParams("www.haidu.com",list));
//        RequestBody body = new FormEncodingBuilder().add("password", "123456789").add("username", "Sunsg11")
//                .add("sign", sign).build();
//
//        Request request = new Request.Builder().url("http://api.breadtrip.com/accounts/login/").post(body).header("User-Agent", "BreadTrip/android/6.0.0/zh (android OS5.0.1) trltechn Map/AutoNavi/v1.4.2 (SM-N9100,samsung)").build();
//

        OkHttpManager.post(Constant.URL_LOGIN).params(list).builder().enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                if (e != null) {
                    Log.i("test", "e.tostring " + e.toString());
                }
            }

            @Override
            public void onResponse(Response response) throws IOException {
                if (response.isSuccessful()) {
                    String value = response.body().string();
                    Log.i("test", "response.body() = " + value);
                    mUser = (User) GsonUtil.fromJson(value, User.class);
                    Log.i("test", "user.tostring() = " + GsonUtil.toJson(mUser));

                    Log.i("test", "response.headers(\"tostring\") = " + response.headers().toString());
//                    uploadTrip();
//                    uploadFile();
                    Headers headers = response.headers();
                    Set<String> sets = headers.names();
                    Iterator<String> it = sets.iterator();
                    while (it.hasNext()) {
                        String name = it.next();
                        Log.i("test", "name = " + name + " values = " + headers.get(name));
                    }

//                    getUserInfo();
//                    getSpotDetail();
                }
            }
        });
//        OkHttpManager.cancelReqest(Constant.URL_LOGIN);
//        OkHttpManager.enqueuePost(Constant.URL_LOGIN, list, new Callback() {
//            @Override
//            public void onFailure(Request request, IOException e) {
//
//            }
//
//            @Override
//            public void onResponse(Response response) throws IOException {
//                if (response.isSuccessful()) {
//                    String value = response.body().string();
//                    Log.i("test", "response.body() = " + value);
//                    mUser = (User) GsonUtil.fromJson(value, User.class);
//                    Log.i("test", "user.tostring() = " + GsonUtil.toJson(mUser));
//
//                    Log.i("test", "response.headers(\"tostring\") = " + response.headers().toString());
////                    uploadTrip();
////                    uploadFile();
//                    Headers headers = response.headers();
//                    Set<String> sets = headers.names();
//                    Iterator<String> it = sets.iterator();
//                    while (it.hasNext()) {
//                        String name = it.next();
//                        Log.i("test", "name = " + name + " values = " + headers.get(name));
//                    }
//                }
//            }
//        });

//        mOkHttpClient.newCall(request).enqueue(new Callback() {
//            @Override
//            public void onFailure(Request request, IOException e) {
//
//            }
//
//            @Override
//            public void onResponse(Response response) throws IOException {
//                if (response.isSuccessful()) {
//                    Log.i("test", "response.body() = " + response.body().string());
//                }
//            }
//        });
    }

    /**
     * 链接网络
     *
     * @param url
     */
    private void connected(final String url) {
        OkHttpManager.enqueue(url, new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                Log.i("test", "链接失败");
            }

            @Override
            public void onResponse(Response response) throws IOException {
                if (response.isSuccessful()) {
                    Headers headers = response.headers();
//                    Set<String> sets= headers.names();
//                    Iterator<String> it = sets.iterator();
//                    while (it.hasNext()){
//                        String name = it.next();
//                        Log.i("test","name = "+ name + " values = "+ headers.get(name));
//                    }
                    String range = headers.get(Constant.KEY_RESPONSE_ACCEPT_RANGES);
                    Log.i("test", "range = " + range);
                    if (Constant.VALUE_RESPONSE_ACCEPT_RANGES.equals(range)) {
                        Log.i("test", "支持断点续传 " + String.valueOf(url.hashCode()));
                        long lengths = response.body().contentLength();
                        File file = new File(StorageUtils.mkdir(), "/" + String.valueOf(url.hashCode()) + ".apk");
                        long tempLength = 0;
                        if (file.exists()) {
                            tempLength = file.length();
                        }
                        downFile(url, tempLength, lengths);

                    }
                }
            }
        });
    }

    /**
     * 下载文件
     *
     * @param url
     * @param tempLength
     * @param totallength
     */
    private void downFile(final String url, final long tempLength, final long totallength) {
        String rangeKey = Constant.KEY_REQUEST_RANGE;
        String rangeValue = String.format(Constant.VALUE_REQUEST_RANGE, tempLength, totallength);
        Headers headers = new Headers.Builder().add(rangeKey, rangeValue).build();
        OkHttpManager.enqueue(url, headers, new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                Log.i("test", "下载失败");
            }

            @Override
            public void onResponse(Response response) throws IOException {
                if (response.isSuccessful()) {
                    Headers headers = response.headers();
                    Set<String> sets = headers.names();
                    Iterator<String> it = sets.iterator();
                    while (it.hasNext()) {
                        String name = it.next();
                        Log.i("test", "name = " + name + " values = " + headers.get(name));
                    }
                    RandomAccessFile accessFile = null;
                    InputStream is = null;
                    try {
                        DecimalFormat df = new DecimalFormat("#.00");
                        is = new BufferedInputStream(response.body().byteStream());
                        File file = new File(StorageUtils.mkdir(), "/" + String.valueOf(url.hashCode()) + ".apk");

//                        if(file.exists()) file.delete();
//                        if(!file.exists()){
//                            file.createNewFile();
//                        }
                        accessFile = new RandomAccessFile(file, "rwd");
                        long lengff = accessFile.length();
                        Log.i("test", "length = " + lengff);
                        if (accessFile.length() >= tempLength) {
                            accessFile.seek(tempLength);
                        }
                        byte[] buffer = new byte[1024 * 16];
                        double temp = tempLength;
                        int len = -1;
                        while ((len = is.read(buffer)) != -1) {
                            accessFile.write(buffer, 0, len);
                            temp = temp + len;
                            Log.i("test1", "present = % " + df.format(temp / totallength * 100) + String.valueOf(url.hashCode()));
                        }

                    } catch (Exception e) {
                        Log.i("test", "exception");
                    } finally {
                        if (is != null) {
                            is.close();
                        }

                        if (accessFile != null) {
                            accessFile.close();
                        }

                        Log.i("test", "final");
                    }
                }
            }
        });
    }


    /**
     * 上传结构trip
     */
    private void uploadTrip() {
        List<KeyValue> list = new ArrayList<KeyValue>();
        list.add(new KeyValue("default", "1"));
        list.add(new KeyValue("privacy", "0"));
        list.add(new KeyValue("wifi_sync", "1"));

        List<UpLoadSpotList> spotList = new ArrayList<UpLoadSpotList>();

        //spot
        UpLoadSpotList spot = new UpLoadSpotList();
        String dateTour = ISODateUtils.format(System.currentTimeMillis());
        spot.setDate_tour(dateTour);
        spot.setIs_hiding_location(false);
        spot.setLocation_alias("");
        spot.setText("乾坤大挪移");

        //spotdtail
        List<SpotDetailList> details = new ArrayList<SpotDetailList>();
        SpotDetailList detail = null;


        String[] paths = new String[]{
                "/storage/emulated/0/DCIM/Camera/20150920_150622.jpg",
                "/storage/emulated/0/DCIM/Camera/20150920_111947.jpg",
                "/storage/emulated/0/DCIM/Camera/20150920_111421.jpg",
                "/storage/emulated/0/DCIM/Camera/20150920_111420.jpg",
                "/storage/emulated/0/DCIM/Camera/20150920_111205.jpg",
                "/storage/emulated/0/DCIM/Camera/20150920_111106.jpg",
                "/storage/emulated/0/DCIM/Camera/20150920_110942.jpg",
                "/storage/emulated/0/DCIM/Camera/20150920_110846.jpg",
                "/storage/emulated/0/DCIM/Camera/20150920_110843.jpg"};
        for (int i = 0; i < paths.length; i++) {
            detail = new SpotDetailList();
            detail.setExif("");
            detail.setType(1);
            detail.setPhoto_date_created(dateTour);
            String key = "photo_d_" + Util.getFormatTime(System.currentTimeMillis(), "yyyy_MM_dd")

                    + "_" + EncodeUtils.encodeMD5(paths[i]) + EncodeUtils.encodeMD5(String.valueOf(System.currentTimeMillis()))

                    + ".jpg";
            detail.setPhoto_key(key);
            details.add(detail);
        }
        //添加 details
        spot.setDetail_list(details);
        //添加上传 spot
        spotList.add(spot);
        String listJson = GsonUtil.toJson(spotList);
        list.add(new KeyValue("spot_list", listJson));
        SecretUtil.getSecretSign(list, getApplicationContext());

        Log.i("test", "params = " + list.toString());
//        OkHttpUtil.enqueuePost(Constant.URL_CREATE_NEW_TRIP,list, new Callback() {
//            @Override
//            public void onFailure(Request request, IOException e) {
//
//            }
//
//            @Override
//            public void onResponse(Response response) throws IOException {
//                if (response.isSuccessful()) {
//                    Log.i("test", "creeate new trip response.body() = " + response.body().string());
//                }
//            }
//        });

    }


    public void uploadFile() {
        String name = "";
        String name1 = "";
        try {
            name = StorageUtils.mkdir() + "/name.png";
            name1 = StorageUtils.mkdir() + "/name1.png";
        } catch (Exception e) {

        }
//
//
        String[] imagePath = {
                name1, name,
                "/storage/emulated/0/DCIM/Camera/20150920_150622.jpg"};
//        String[] imagePath = {
//                "/storage/emulated/0/DCIM/Camera/20150924_123842.jpg",
//                "/storage/emulated/0/DCIM/Camera/20150924_123728.jpg",
//                "/storage/emulated/0/DCIM/Camera/20150922_193500.jpg",
//                "/storage/emulated/0/DCIM/Camera/20150802_113605.jpg",
//                "/storage/emulated/0/DCIM/Camera/20150802_113557.jpg",
//                "/storage/emulated/0/DCIM/Camera/20150803_194524.jpg"};
        for (int i = 0; i < imagePath.length; i++) {
            List<KeyValue> list = new ArrayList<KeyValue>();
            list.add(new KeyValue("trip_id", "2388025839"));
            list.add(new KeyValue("time", System.currentTimeMillis() + ""));
            list.add(new KeyValue("timezone", "Asia/Shanghai"));
            list.add(new KeyValue("text", "哈哈哈" + i));
            list.add(new KeyValue("sync", ""));
            list.add(new KeyValue("privacy", "0"));
            list.add(new KeyValue("cover", ""));

            String exif = "{\"VERSION\":\"ANDROID\",\"{TIFF}\":{\"DateTime\":\"2015:09:24 12:37:28\",\"ExposureTime\":\"0.0017\",\"FNumber\":\"2.2\",\"Flash\":\"0\",\"FocalLength\":\"480\\/100\",\"ISOSpeedRatings\":\"8000\",\"ImageLength\":\"2988\",\"ImageWidth\":\"5312\",\"Make\":\"samsung\",\"Model\":\"SM-N9100\",\"Orientation\":\"6\",\"WhiteBalance\":\"0\"}}";
            list.add(new KeyValue("exif", exif));
            SecretUtil.getSecretSign(list, getApplicationContext());

            KeyValue fileParam = new KeyValue("photo", imagePath[i]);
            String url = String.format(Constant.URL_ADD_TRACK, "2387099798");
            OkHttpManager.post(url).params(list).fileParam(fileParam).builder().enqueue(new Callback() {
                @Override
                public void onFailure(Request request, IOException e) {
                    Log.i("test", "add track response = not success");
                    Log.i("test", "response tag = " + request.tag().toString());
                }

                @Override
                public void onResponse(Response response) throws IOException {
                    if (response.isSuccessful()) {
                        Log.i("test", "response.headers(\"tostring\") = " + response.headers().toString());
                        Log.i("test", "add track response = " + response.body().string());
                    }
                }
            });

//            OkHttpManager.enqueuePost(url, list, fileParam, new Callback() {
//                @Override
//                public void onFailure(Request request, IOException e) {
//                    Log.i("test", "add track response = not success");
//                    Log.i("test", "response tag = " + request.tag().toString());
//                }
//
//                @Override
//                public void onResponse(Response response) throws IOException {
//                    if (response.isSuccessful()) {
//                        Log.i("test", "add track response = " + response.body().string());
//                    }
//
//                }
//            });

        }

        Log.i("test", "complete");


//        /storage/emulated/0/DCIM/Camera/20150924_123842.jpg
//        /storage/emulated/0/DCIM/Camera/20150924_123728.jpg
//        /storage/emulated/0/DCIM/Camera/20150922_193500.jpg
//        /storage/emulated/0
//        /storage/emulated/0/DCIM/Camera/20150803_194524.jpg
//        /storage/emulated/0/DCIM/Camera/20150802_113605.jpg
//        /storage/emulated/0/DCIM/Camera/20150802_113557.jpg

    }


    /***
     * 跳转到fresco加载图片页面
     */
    public void jumpFrescoActivity() {
        Intent intent = new Intent(MainActivity.this, FrescoImageActivity.class);
        startActivity(intent);
    }

    /**
     * 压缩图片
     */

    public void compressPic() {
        String path = "/storage/emulated/0/DCIM/Camera/20150920_150622.jpg";
        String target = StorageUtils.mkdir() + "/name2.jpg";
//                    StorageUtils.delete(new File(target));
        Log.i("test", "size = " + StorageUtils.getFileSize(path));
        ImageUtil.commonCompressPic(path, target, 1080, 1080);
        Log.i("test", "size = " + StorageUtils.getFileSize(target));
    }

    /**
     * 加载本地html
     */
    private void localHtml() {
        Intent intent = new Intent(this, LongImageWebViewActivity.class);
        startActivity(intent);
    }

    /**
     * 下拉延伸图片
     */
    private void pollToZoone() {
        Intent intent = new Intent(this, PullToZoonActivity.class);
        startActivity(intent);
    }

    /**
     * 线程池
     */
    private void threadPool() {
        ThreadPoolManager threadPool = ThreadPoolManager.getInstance();
        int produceTaskSleepTime = 2;
        int produceTaskMaxNumber = 50;
        for (int i = 0; i < produceTaskMaxNumber; i++) {
            try {
                // 产生一个任务，并将其加入到线程池
                String task = "task@ " + i;
                Log.i("test", "put " + task);
//                System.out.println("put " + task);
                threadPool.addTask(new CompressImageTask(task, callBack));

                // 便于观察，等待一段时间
//                Thread.sleep(produceTaskSleepTime);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Log.e("test", "count = " + threadPool.getThreadPoolExecutor().getActiveCount());

    }

    private CallBack callBack = new CallBack() {
        @Override
        public void call(Object object) {

        }
    };

    /**
     * litepal 数据库
     */
    private void litepal() {
        /**litepal 获得数据库*/
        Introduction introduction = new Introduction();
        introduction.setGuide("ggggggg");
        introduction.setDigest("dddddd");
        introduction.save();
        News news = new News();
        news.setTitle("guilde");
        news.setContent("introduction content");
        news.setIntroduction(introduction);
        news.save();
//        DemoDb demo = new DemoDb();
//        demo.setTitle("第一条数据");
////        demo.setContent("内容随便写");
//        demo.setNotSave("save");
//        demo.setSubContent("subcontent");
//        boolean save = demo.save();
//        demo.setDdd("ddd");
//        Log.i("test", "saved = " + save + "id = " + demo.getId());
//
//        News news = new News();
//        News news1 = new News();
//        Comment comment1 = new Comment();
//        Comment comment2 = new Comment();
//
//        comment1.setContent("第一个评论");
//        comment2.setContent("第二个评论");
//
//        news.setTitle("new 1");
//        news.setContent("第一条新闻");
//
//        news1.setTitle("new 2");
//        news1.setContent("第二条评论");
//
//        comment1.save();
//        comment2.save();
//
//        List<Comment> comments = new ArrayList<>();
//        comments.add(comment1);
//        comments.add(comment2);
//        news.setCommentList(comments);
//        boolean newSave = news.save();
//        Log.i("test", "newSave  = " + newSave + "id = " + news.getId());
        //更新id为 2 的记录
//        News news = new News();
//        news.setContent("content update");
//        news.update(2);

//        News news = new News();
//        news.setContent("update alls");
//        news.updateAll("content = ?","第一条新闻");//更新 content 字段 为 第一条新闻 的 所有记录 为 update alls

//        News news = new News();
//        news.setContent("我的 大家是否了解");
//        news.updateAll("content = ? and title = ?","第二条评论","new 2");

//        News news = new News();
//        news.setToDefault("title"); //表中title字段 设置为默认值
//        news.updateAll();

        //删除所有数据
//        DataSupport.deleteAll(News.class);

//        DataSupport.deleteAll(News.class,"content = ? and title = ?","第二条评论","");
//        DataSupport.delete(News.class,1);
//        News news = new News();
//        if(news.isSaved()){
//            news.delete();
//        }

        List<News> ss = DataSupport.findAll(News.class, true);
        if (ss != null) {
            Log.i("test", ss.toString());
            for (News nn : ss) {
                List<Comment> comments = nn.getCommentList();
                if (comments != null) {
                    for (Comment com : comments) {
                        if (com.getId() == 3) {
                            com.delete();
                        }
                        Log.i("test", "comment = " + com.toString());
                    }
                }
            }
        }


    }


//    [trip_id=2388025839, time=1.443069448E9, timezone=Asia/Shanghai, text=, sync=, privacy=0, cover=, exif={"VERSION":"ANDROID","{TIFF}":{"DateTime":"2015:09:24 12:37:28","ExposureTime":"0.0017","FNumber":"2.2","Flash":"0","FocalLength":"480\/100","ISOSpeedRatings":"8000","ImageLength":"2988","ImageWidth":"5312","Make":"samsung","Model":"SM-N9100","Orientation":"6","WhiteBalance":"0"}}]
//
//            [photo=/storage/emulated/0/aoyouji/breadtrip/.track/photo/3/1444443866346.jpg]


//    "http://photos.breadtrip.com/photo_d_2015_08_17_6e621ce88cf3261210752b51bde79c51d296586b789c3b858f67b9de751a0dc5.jpg?imageView/1/w/640/h/480/q/85"
//    w = photo_width: 1200,photo_height: 1600

    //    "http://photos.breadtrip.com/photo_d_2015_08_17_4aefa0de16407f842b4e1cd40b1ac37aea9c6a1ae68e5bd2aa7ee09d76e4cc75.jpg?imageView/2/w/960/q/85"
//    w = 648
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //上传文件
            case R.id.button_upload_file:
                uploadFile();
                break;
            //fresco加载图片
            case R.id.button_fresco:
                jumpFrescoActivity();
                break;
            //压缩图片
            case R.id.button_compress_pic:
                compressPic();

                break;
            //压缩图片
            case R.id.button_local_html:
                localHtml();
                break;
            case R.id.btn_pullto_zone:
                //下拉图片
                pollToZoone();
                break;
            case R.id.btn_thread_pool:
                //线程池
                threadPool();
            case R.id.button_download_apk:
                //下载apk
                String urlTaoBao = Constant.URL_DOWN_TAOBAO_APK_URL;
                String pathTaoBao = StorageUtils.mkdir() + File.separator + DownLoadFileUtil.parseFileName(urlTaoBao) + ".apk";
                new DownLoadFileUtil.Builder().url(urlTaoBao).path(pathTaoBao).tag(urlTaoBao).onDownLoadFileListener(onDownLoadFileListener).builder().startConnect();
                break;
            case R.id.button_cancel_download:
                //取消下载
                String urlYouKu = Constant.URL_DOWN_YOUKU_APK_URL;
                String pathYouKu = StorageUtils.mkdir() + File.separator + DownLoadFileUtil.parseFileName(urlYouKu) + ".apk";
                new DownLoadFileUtil.Builder().url(urlYouKu).path(pathYouKu).tag(urlYouKu).onDownLoadFileListener(onDownLoadFileListener).builder().startConnect();
                break;
            case R.id.btn_second_activity:
                //ipc 绑定另一个进程中的serviece
                Intent intent = new Intent(MainActivity.this, ProcessServiceCommunicationActivity.class);
                startActivity(intent);
                break;
            case R.id.btn_serviece_bindpool:
                //ipc 绑定另一个进程中的serviece 使用binderpool
                Intent intent2 = new Intent(MainActivity.this, BinderPoolManagerActivity.class);
                startActivity(intent2);
                break;
            case R.id.btn_horizen_scroll_view:
                Intent intent3 = new Intent(MainActivity.this, HorizontalScrollViewWithListViewActivity.class);
                startActivity(intent3);
                break;

            case R.id.btn_litepal:
                litepal();
                break;
            case R.id.button_sunsg:
                Intent intentSunsg = new Intent(MainActivity.this, SunsgActivity.class);
                startActivity(intentSunsg);
                break;
            //自定义view
            case R.id.btn_auto_view:
                AutoActivity.launch(MainActivity.this);
                break;
            //RecyclerView
            case R.id.btn_recycle:
                RecyclerViewActivity.launch(MainActivity.this);
                break;
            case R.id.btn_slide_item:
                SlideRemoveActivity.launch(MainActivity.this);
                break;
            case R.id.btn_eventbus3:
                EventBusActivity.launch(MainActivity.this);
                break;
            case R.id.btn_annotation:
                AnnotationActivity.launch(MainActivity.this);
                break;
            case R.id.btn_retrofit:
                RetrofitActivity.launch(MainActivity.this);
                break;
            case R.id.btn_desgin_model:
                DesignModelActivity.launch(MainActivity.this);
                break;
            case R.id.btn_rx_java:
                RxJavaActivity.launch(MainActivity.this);
                Util.putChannelName(getApplicationContext(), "dksjfksjlf");
                Util.getChannelName(getApplicationContext());
                break;
            case R.id.btn_screen_shots:
                Toast.makeText(getApplicationContext(), "截图", Toast.LENGTH_SHORT).show();
                screenShot(scrollviewRoot);
                break;
            case R.id.btn_wave_view:
                WaveViewActivity.launch(MainActivity.this);
                break;
            case R.id.touch_activity:
                TouchActivity.launch(MainActivity.this);
                break;
            case R.id.btn_glide:
                GlideActivity.launch(MainActivity.this);
                break;
            case R.id.btn_bitmap_shader:
                BitmapShaderActivity.launch(MainActivity.this);
                break;
            case R.id.btn_float_activity:
                FloatViewActivity.launch(MainActivity.this);
                break;
            case R.id.btn_thread_pool_activity:
                ThreadPoolTestActivity.launch(MainActivity.this);
                break;
            case R.id.btn_slide_left_up:
                SlideLeftAndUpActivity.launch(MainActivity.this);
                break;
            case R.id.btn_constraintLayout:
                BaseActivityActivity.launch(this, ConstraintLayoutActivity.class);
                break;

            case R.id.btn_camera:
                BaseActivityActivity.launch(this, CameraActivity.class);
                break;
            case R.id.btn_moveview:
                BaseActivityActivity.launch(this, MoveViewActivity.class);
                break;
        }
    }

    private DownLoadFileUtil.OnDownLoadFileListener onDownLoadFileListener = new DownLoadFileUtil.OnDownLoadFileListener() {
        @Override
        public void onStart() {
            Log.i("test", "开始下载");
        }

        @Override
        public void onProgress(long finished, long total, Object tag) {
            if (tag instanceof String) {
                if (tag.equals(Constant.URL_DOWN_YOUKU_APK_URL)) {
                    mProgressBarYouKu.setProgress((int) (((double) finished / total) * 100));
                    mTvYouKu.setText(StorageUtils.size(finished) + "/" + StorageUtils.size(total));
                } else if (tag.equals(Constant.URL_DOWN_TAOBAO_APK_URL)) {
                    mProgressBarTaoBao.setProgress((int) (((double) finished / total) * 100));
                    mTvTaoBao.setText(StorageUtils.size(finished) + "/" + StorageUtils.size(total));
                }
                Log.i("test", StorageUtils.size(finished) + "/" + StorageUtils.size(total) + " " + tag);
            }
        }

        @Override
        public void onPause() {
            Log.i("test", "onPause");
        }

        @Override
        public void onComplete() {
            Log.i("test", "onComplete");
        }

        @Override
        public void onCancel() {
            Log.i("test", "onCancel");
        }

        @Override
        public void onFailure(String message) {
            Log.i("test", message);
        }
    };

    private void screenShot(View v) {
//        ScreenShotsUtil.normalScreenShots(v);
//        ScreenShotsUtil.screenShots(MainActivity.this);
        WebviewActivity.startActivity(MainActivity.this, "http://puddings.roobo.com/apphelp/");
    }


}

class TestHeapClass extends Thread {
    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(60 * 60 * 1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

